<template>
  <div class="users-container">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
      <el-breadcrumb-item>
        <i class="el-icon-arrow-right"></i>
        活动详情
      </el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域start -->
    <el-card>
      <div>
        <!-- 卡片头部区域start -->
        <div class="card_header">
          <div class="card_header_input">
            <el-input
              placeholder="请输入内容"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList()"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList()"
              ></el-button>
            </el-input>
          </div>
          <el-button
            class="addBtn"
            type="primary"
            @click="addUserDialogVisible = true"
          >
            添加用户
          </el-button>
        </div>
        <!-- 卡片头部区域end -->

        <!-- 卡片表格区域start -->
        <div class="el_card_table">
          <el-table :data="userList" border stripe style="width: 100%;">
            <el-table-column type="index" align="center"></el-table-column>
            <el-table-column
              prop="username"
              label="姓名"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="email"
              label="邮箱"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="mobile"
              label="电话"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="role_name"
              label="角色"
              align="center"
            ></el-table-column>
            <el-table-column prop="mg_state" label="状态" align="center">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.mg_state"
                  @change="userStateChanged(scope.row)"
                ></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="role_name" label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editUserBtnClick(scope.row)"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteUserBtn(scope.row.id)"
                ></el-button>
                <el-button
                  type="warning"
                  icon="el-icon-setting"
                  size="mini"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 卡片表格区域end -->

        <!-- 分页区域start -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
        <!-- 分页区域end -->
      </div>
    </el-card>
    <!-- 卡片视图区域end -->

    <!-- 对话框start -->
    <el-dialog
      title="添加用户"
      :visible.sync="addUserDialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <el-form
        :model="addUserForm"
        :rules="addUserRules"
        ref="addUserFormRef"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名 :" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码 :" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱 :" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号 :" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="isSureAddUser">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editUserDialogVisible"
      width="30%"
      @close="editDialogClosed"
    >
      <el-form
        ref="editFormRef"
        :rules="addUserRules"
        :model="editUserInfo"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editUserInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editUserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <!-- 删除用户对话框 -->

    <!-- 对话框end -->
  </div>
</template>

<script>
/* api */
import { getUserListApi } from '@/api/HomeApi/HomeApi.js'
import { changeUserStateApi } from '@/api/HomeApi/HomeApi.js'
import { addUserApi } from '@/api/HomeApi/HomeApi.js'
import { editUserInfoApi } from '@/api/HomeApi/HomeApi.js'
import { deleteUserApi } from '@/api/HomeApi/HomeApi.js'

export default {
  name: 'Users',
  data() {
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      //获取到的用户列表数据
      userList: [],
      total: 0,

      /* 对话框区域 */
      addUserDialogVisible: false,
      addUserForm: {
        username: '',
        email: '',
        password: '',
        mobile: '',
      },
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      },
      editUserDialogVisible: false,
      editUserInfo: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    async getUserList() {
      const { data: res } = await getUserListApi(this.queryInfo)
      if (res.meta.status !== 200) {
        return
      } else {
        this.userList = res.data.users
        this.total = res.data.total
      }
    },

    /* 表格区域 */
    //修改用户状态
    async userStateChanged(userInfo) {
      const { data: res } = await changeUserStateApi(userInfo)
      if (res.meta.status !== 200) {
        return this.$message.error('修改用户状态失败')
      }
    },

    /* 分页区域 */
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },

    /* 对话框区域 */
    //添加用户对话框
    addDialogClosed() {
      this.$refs.addUserFormRef.resetFields()
    },
    isSureAddUser() {
      this.$refs.addUserFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('添加用户信息失败')
        } else {
          const { data: res } = await addUserApi(this.addUserForm)
          if (res.meta.status !== 201) {
            return this.$message.error('创建用户失败')
          } else {
            this.addUserDialogVisible = false
            this.$message.success('创建用户成功')
            this.getUserList()
          }
        }
      })
    },
    //修改用户对话框
    editUserBtnClick(userInfo) {
      this.editUserDialogVisible = true
      this.editUserInfo = userInfo
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
      this.getUserList()
    },
    submitEditForm() {
      this.editUserDialogVisible = false
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message.error('修改用户信息失败')
        } else {
          const { data: res } = await editUserInfoApi(this.editUserInfo)
          if (res.meta.status !== 200) {
            return this.$message.error('更新失败')
          }
          //editUserInfo信息只在点击按钮时传递过来也存储到表单里，所以一直是未修改的信息
          //表单就一直保存着未修改的信息 所以表单也需要更新数据
          this.editUserInfo = res.data
          this.getUserList()
        }
      })
    },
    
    //删除用户
    async deleteUserBtn(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).catch((err) => {
        return err
      })
      if (confirmResult === 'confirm') {
        const { data: res } = await deleteUserApi(parseInt(id))
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        } else {
          this.getUserList()
          return this.$message.success('删除成功')
        }
      } else {
        return this.$message.info('已取消了删除')
      }
    },
  },
  watch: {},
}
</script>

<style lang="less" scoped>
.el-icon-arrow-right {
  color: rgb(199, 198, 198);
  margin-left: -12px;
  font-size: 14px;
}
.el-card {
  margin-top: 20px;
}
.card_header {
  width: 1200px;
  display: flex;
  margin: 0 auto;
}
.card_header_input {
  width: 300px;
}
.addBtn {
  margin-left: 20px;
}
.el_card_table {
  width: 1200px;
  margin: 0 auto;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 10px;
}
</style>
